package cn.ydt.ydt.shopping.webapi.service.impl;

import cn.ydt.ydt.common.utils.FileNameUtils;
import cn.ydt.ydt.pojo.shopping.model.Vegetable;
import cn.ydt.ydt.pojo.shopping.model.VegetableElastic;
import cn.ydt.ydt.shopping.service.ISearchService;
import cn.ydt.ydt.shopping.webapi.mapper.IVegetableMapper;
import cn.ydt.ydt.shopping.webapi.repository.VegetableRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SerachServiceImpl implements ISearchService {

    @Autowired
    private IVegetableMapper vegetableMapper;

    @Autowired
    private VegetableRepository vegetableRepository;


    public void loadVegetable(){
        //查询所有的菜品信息
        List<Vegetable> vegetableList = vegetableMapper.getAllVegetableList();
        List<VegetableElastic> vegetableElastics = new ArrayList<>();
        for (Vegetable vegetable : vegetableList){
            VegetableElastic vegetableElastic = new VegetableElastic();
            BeanUtils.copyProperties(vegetable,vegetableElastic);
            vegetableElastics.add(vegetableElastic);
        }
        vegetableRepository.saveAll(vegetableElastics);
    }

    public void clearVegetable(){
        vegetableRepository.deleteAll();
    }


    @Override
    public List<VegetableElastic> search(String keyword) {
        Iterable<VegetableElastic> vegetableElastics = vegetableRepository.queryVegetableElasticByVegetableNameMatches(keyword);
        List<VegetableElastic> list = new ArrayList<>();
        vegetableElastics.forEach(e ->{list.add(e);});
        for (VegetableElastic v : list){
            String img = v.getVegetableImage();
            v.setVegetableImage(FileNameUtils.filePath(img));
        }
        return list;
    }
}
